package com.ruoyi.business.youdaoController;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.net.MediaType;
import com.ruoyi.business.services.HttpService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SaveType;
import com.ruoyi.common.utils.GetUrlParam;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.domain.vo.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import static org.aspectj.weaver.Iterators.append;

@RestController
@RequestMapping("ownZijieRtaApi")
public class WifiToZiJieController {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private HttpService httpService;

    private final static String CLASSESEN = "youdao";

    /**
     * 优酷 -> 抖音RTA
     * @param request
     * @return
     * @throws Exception
     */
    @Log(title = "有道", businessType = BusinessType.RTA, esIndex = "youdao_log", saveType = SaveType.ES)
    @RequestMapping("/youku_rta")
    public Object rtaSend(HttpServletRequest request, @RequestBody JSONObject params) throws Exception {
        String queryString = request.getQueryString();
        Map<String, Object> queryMap = GetUrlParam.queryStrToMap(queryString);
        String channelId = queryMap.get("channelId") + "";

        String dmpid = params.getString("reqId");
        String reqTime = params.getString("reqTime");
        JSONObject deviceinfoInput = params.getJSONObject("deviceInfo");
        JSONArray rtaIdList = params.getJSONArray("rtaIdList");

        String os = deviceinfoInput.getString("os");
        String caid1 = deviceinfoInput.getOrDefault("caid1", "") + "";
        String caid1Version = deviceinfoInput.getOrDefault("caid1Version", "") + "";
        String caid2 = deviceinfoInput.getOrDefault("caid2", "") + "";
        String caid2Version = deviceinfoInput.getOrDefault("caid2Version", "")+ "";
        String androidIdMd5 = deviceinfoInput.getOrDefault("androidIdMd5", "")+ "";
        String imeiMd5 = deviceinfoInput.getOrDefault("imeiMd5", "") + "";
        String oaid = deviceinfoInput.getOrDefault("oaid", "") + "";
        String idfaMd5 = deviceinfoInput.getOrDefault("idfaMd5", "") + "";
        String rtaId = "";
        String advertiserId = "";
        try{
            rtaId = rtaIdList.getJSONObject(0).getOrDefault("rtaId", "")+ "";
            advertiserId = rtaIdList.getJSONObject(0).getOrDefault("advertiserId", "")+"";
        }catch (Exception e){
        }


        String ip = IpUtils.getIpAddr(request);
        String ua = request.getHeader("User-Agent");


        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("reqId不能为空");
        }

        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        if("0".equals(channelDetail.get("isopen")+"")){
            return R.failure().msg("channelId未开启");
        }

        String url = channelDetail.get("rta_adress") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);



        bytedance_growth_rta.RtaProtoCpa.Request.Builder builder = bytedance_growth_rta.RtaProtoCpa.Request.newBuilder();
        builder.setName("XINYOU");
        builder.setRequestId(dmpid);

        bytedance_growth_rta.RtaProtoCpa.DeviceInfo.Builder deviceInfo = bytedance_growth_rta.RtaProtoCpa.DeviceInfo.newBuilder();
        deviceInfo.setDeviceModel("");
        deviceInfo.setOaid(oaid);
        deviceInfo.setOaidMd5("");
        deviceInfo.setImei("");
        deviceInfo.setImeiMd5(imeiMd5);
        deviceInfo.setIdfa("");
        deviceInfo.setIdfaMd5(idfaMd5);

        bytedance_growth_rta.RtaProtoCpa.CaidInfo.Builder caidInfo = bytedance_growth_rta.RtaProtoCpa.CaidInfo.newBuilder();
        caidInfo.setCaid1(caid1);
        caidInfo.setCaidVersion1(caid1Version);
        caidInfo.setCaid2(caid2);
        caidInfo.setCaidVersion2(caid2Version);
        deviceInfo.setCaidInfo(caidInfo.build());
        builder.setDeviceInfo(deviceInfo.build());
        builder.setRit(advertiserId);
        builder.setIp(ip);
        builder.setUa(ua);

        bytedance_growth_rta.RtaProtoCpa.Request build = builder.build();
        byte[] data = build.toByteArray();

        // 生成签名
        String signKey = "PPn4j03qJ5bliNzQbFYJQOyRhm3rOARAAAlLnEEu+bE=";
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] digest = md.digest(append(data, signKey.getBytes(StandardCharsets.UTF_8)));
        String signature = DatatypeConverter.printHexBinary(digest);
        //转为小写
        signature = signature.toLowerCase();

        try{
//            long startTime = System.currentTimeMillis();
            //使用hutool发送post
            String post = HttpUtil.createPost(requestAddress)
                    .header("Content-Type", "application/x-protobuf")
                    .header("X-RTA-API-SIGN", signature)
                    .body(data)
                    .execute().body();
//            System.out.println("发送RTA请求耗时：" + (System.currentTimeMillis() - startTime));
            //获取byte数组
            byte[] bytes = post.getBytes();
            //解析byte数组
            bytedance_growth_rta.RtaProtoCpa.Response response = bytedance_growth_rta.RtaProtoCpa.Response.parseFrom(bytes);
            if(response.getStatusCode() == 0){
                return new JSONObject().fluentPut("code", 0).fluentPut("reqId", dmpid).fluentPut("accept", "Y");
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return new JSONObject().fluentPut("code", 0).fluentPut("reqId", dmpid).fluentPut("accept", "N");
    }




    /**
     * wifi -> 字节
     * https://www.ssptqt.com/ownZijieRtaApi/rta?channelId=7153104986179584&dmpid=__SID__&imei=__IMEI__&imei_md5=__HASH_IMEI__&idfa=__IDFA__&idfa_md5=__HASH_IDFA__&oaid=__OAID__&oadi_md5=&ts=__STIME__&os=__OS__&ua=&ip=&caid=&androidid_md5=__ANDROID_ID__&mac_md5=__MAC__
     *
     * 喜马拉雅 -> 字节
     * http://47.94.2.84:9185/ownZijieRtaApi/rta?channelId=&dmpid=_TS_&imei=&imei_md5=_IMEI_MD5_&idfa=_IDFA_&idfa_md5=&oaid=_OAID_&oadi_md5=&ts=_TS_&request_id=_TS_&os=_OS_&ua=&ip=&ip_md5=&caid=&android_id_md5=&mac_md5=
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Log(title = "有道", businessType = BusinessType.RTA, esIndex = "youdao_log", saveType = SaveType.ES)
    @RequestMapping("/rta")
    public Object rtaSend(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");

        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        if("0".equals(channelDetail.get("isopen")+"")){
            return R.failure().msg("channelId未开启");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);
        String ua = baseParamsMap.get("ua") + "";
        String ip = baseParamsMap.get("ip") + "";
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){
            ua = URLDecoder.decode(ua, Constants.UTF8);
        }else{
            //request 获取 ua
            ua = request.getHeader("User-Agent");
            baseParamsMap.put("ua", URLEncoder.encode(ua, Constants.UTF8));
        }
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){
        }else{
            //request 获取 ip
            ip = IpUtils.getIpAddr(request);
            baseParamsMap.put("ip", ip);
        }

        String url = channelDetail.get("rta_adress") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        baseParamsMap.putAll(staticParamsMap);

        // string device_model = 1;    // 机型
        //    string oaid = 2;            // oaid原值
        //    string oaid_md5 = 3;        // oaid原值的md5
        //    string imei = 4;            // imei原值
        //    string imei_md5 = 5;        // imei原值的md5
        //    string idfa = 6;            // idfa原值
        //    string idfa_md5 = 7;        // idfa原值的md5
        //    CaidInfo caid_info = 8;     // caid信息

        String oaid= baseParamsMap.get("oaid") + "";
        String oaidMd5= baseParamsMap.get("oaid_md5") + "";
        String imei= baseParamsMap.get("imei") + "";
        String imeiMd5= baseParamsMap.get("imei_md5") + "";
        String idfa= baseParamsMap.get("idfa") + "";
        String idfaMd5= baseParamsMap.get("idfa_md5") + "";
        String caid= baseParamsMap.get("caid") + "";
        String rit= baseParamsMap.get("rit") + "";
        String ipTemp = baseParamsMap.get("ip") + "";
        String uaTemp = baseParamsMap.get("ua") + "";



        bytedance_growth_rta.RtaProtoCpa.Request.Builder builder = bytedance_growth_rta.RtaProtoCpa.Request.newBuilder();
        builder.setName("XINYOU");
        builder.setRequestId(dmpid);

        bytedance_growth_rta.RtaProtoCpa.DeviceInfo.Builder deviceInfo = bytedance_growth_rta.RtaProtoCpa.DeviceInfo.newBuilder();
        deviceInfo.setDeviceModel("");
        deviceInfo.setOaid(oaid);
        deviceInfo.setOaidMd5(oaidMd5);
        deviceInfo.setImei(imei);
        deviceInfo.setImeiMd5(imeiMd5);
        deviceInfo.setIdfa(idfa);
        deviceInfo.setIdfaMd5(idfaMd5);

        bytedance_growth_rta.RtaProtoCpa.CaidInfo.Builder caidInfo = bytedance_growth_rta.RtaProtoCpa.CaidInfo.newBuilder();
        caidInfo.setCaid1(caid);
        caidInfo.setCaid2(caid);
        deviceInfo.setCaidInfo(caidInfo.build());
        builder.setDeviceInfo(deviceInfo.build());
        builder.setRit(rit);
        builder.setIp(ipTemp);
        builder.setUa(uaTemp);

        bytedance_growth_rta.RtaProtoCpa.Request build = builder.build();
        byte[] data = build.toByteArray();

        // 生成签名
        String signKey = "PPn4j03qJ5bliNzQbFYJQOyRhm3rOARAAAlLnEEu+bE=";
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] digest = md.digest(append(data, signKey.getBytes(StandardCharsets.UTF_8)));
        String signature = DatatypeConverter.printHexBinary(digest);
        //转为小写
        signature = signature.toLowerCase();


        try{
//            long startTime = System.currentTimeMillis();
            //使用hutool发送post
            String post = HttpUtil.createPost(requestAddress)
                    .header("Content-Type", "application/x-protobuf")
                    .header("X-RTA-API-SIGN", signature)
                    .body(data)
                    .execute().body();
//            System.out.println("发送RTA请求耗时：" + (System.currentTimeMillis() - startTime));
            //获取byte数组
            byte[] bytes = post.getBytes();
            //解析byte数组
            bytedance_growth_rta.RtaProtoCpa.Response response = bytedance_growth_rta.RtaProtoCpa.Response.parseFrom(bytes);
            if(response.getStatusCode() == 0){
                return 1;
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

        return 0;
    }

    public static byte[] append(byte[] data, byte[] signKey) {
        byte[] result = new byte[data.length + signKey.length];
        System.arraycopy(data, 0, result, 0, data.length);
        System.arraycopy(signKey, 0, result, data.length, signKey.length);
        return result;
    }



    private String getMapValue(Map<String, Object> map, String key){
        if(map == null){
            return "";
        }
        if(map.get(key) == null){
            return "";
        }
        return map.get(key)+"";
    }

    public static void main(String[] args) {
        try {
            // 创建Request消息
            bytedance_growth_rta.RtaProtoCpa.Request req = bytedance_growth_rta.RtaProtoCpa.Request.newBuilder()
                    .setName("XINYOU")
                    .setRequestId("123456")
                    .addAllRtaTokens(Arrays.asList("token1", "token2"))
                    .setDeviceInfo(bytedance_growth_rta.RtaProtoCpa.DeviceInfo.newBuilder()
                            .setDeviceModel("Pixel 5")
                            .setOaid("oaid_value")
                            .setOaidMd5("oaid_md5_value")
                            .setImei("imei_value")
                            .setImeiMd5("imei_md5_value")
                            .setIdfa("idfa_value")
                            .setIdfaMd5("idfa_md5_value")
                            .setCaidInfo(bytedance_growth_rta.RtaProtoCpa.CaidInfo.newBuilder()
                                    .setCaid1("caid_high")
                                    .setCaidVersion1("v1")
                                    .setCaid2("caid_low")
                                    .setCaidVersion2("v2")
                                    .build())
                            .build())
                    .setRit("ad_slot_001")
                    .setIp("192.168.1.1")
                    .setUa("Mozilla/5.0")
                    .putAllUserLabel(new HashMap<String, String>() {{
                        put("key1", "value1");
                        put("key2", "value2");
                    }})
                    .build();

            // 序列化Request消息
            byte[] data = req.toByteArray();

            // 生成签名
            String signKey = "PPn4j03qJ5bliNzQbFYJQOyRhm3rOARAAAlLnEEu+bE=";

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] digest = md.digest(append(data, signKey.getBytes(StandardCharsets.UTF_8)));
            String signature = DatatypeConverter.printHexBinary(digest);


            //转为小写
            signature = signature.toLowerCase();


            // 创建HTTP请求
            String requestAddress = "https://bytedanceugrta.bytedance.com/ugrta/common";

            String post = HttpUtil.createPost(requestAddress)
                    .header("Content-Type", "application/x-protobuf")
                    .header("X-RTA-API-SIGN", signature)
                    .body(data)
                    .execute().body();
            //获取byte数组
            byte[] bytes = post.getBytes();
            //解析byte数组
            bytedance_growth_rta.RtaProtoCpa.Response response = bytedance_growth_rta.RtaProtoCpa.Response.parseFrom(bytes);
            System.out.println(response.getStatusCode());
            System.out.println(response.getMsg());
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }
    }



}
